/** 模拟网络请求的延迟 */
function delay(ms = 500) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

const { convertCloudUrl } = require('../utils/util');

// 模拟消息数据
const mockMessageList = [
  {
    userId: 'user001',
    name: 'Sean',
    avatar: convertCloudUrl('@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/chat/avatar-Sean.png'),
    messages: [
      {
        messageId: 'msg001',
        from: 'user001',
        content: '你好，我是Sean，很高兴认识你！',
        time: Date.now() - 300000,
        read: false,
      },
      {
        messageId: 'msg002',
        from: 'me',
        content: '你好！很高兴认识你',
        time: Date.now() - 240000,
        read: true,
      },
    ],
  },
  {
    userId: 'user002',
    name: 'Mollymolly',
    avatar: convertCloudUrl('@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/chat/avatar-Mollymolly.png'),
    messages: [
      {
        messageId: 'msg003',
        from: 'user002',
        content: '最近在忙什么项目呢？',
        time: Date.now() - 240000,
        read: false,
      },
    ],
  },
  {
    userId: 'user003',
    name: 'Andrew',
    avatar: convertCloudUrl('@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/chat/avatar-Andrew.png'),
    messages: [
      {
        messageId: 'msg004',
        from: 'user003',
        content: '我在开发一个新的小程序',
        time: Date.now() - 180000,
        read: true,
      },
    ],
  },
  {
    userId: 'user004',
    name: 'Kingdom',
    avatar: convertCloudUrl('@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/chat/avatar-Kingdom.png'),
    messages: [
      {
        messageId: 'msg005',
        from: 'user004',
        content: '听起来很有趣，需要帮忙吗？',
        time: Date.now() - 120000,
        read: false,
      },
    ],
  },
  {
    userId: 'user005',
    name: 'Paige',
    avatar: convertCloudUrl('@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/chat/avatar-Paige.png'),
    messages: [
      {
        messageId: 'msg006',
        from: 'user005',
        content: '我也想参与进来！',
        time: Date.now() - 60000,
        read: false,
      },
    ],
  },
];

/** 获取未读消息数量 */
function fetchUnreadNum() {
  return new Promise((resolve) => {
    setTimeout(() => {
      let unreadCount = 0;
      mockMessageList.forEach(user => {
        unreadCount += user.messages.filter(msg => !msg.read && msg.from !== 'me').length;
      });
      resolve({
        success: true,
        data: unreadCount,
      });
    }, 300);
  });
}

/** 模拟WebSocket连接 */
function connectSocket() {
  const mockSocket = {
    onMessage: (callback) => {
      // 模拟接收消息
      setInterval(() => {
        if (Math.random() > 0.9) { // 10%概率收到新消息
          const randomUser = mockMessageList[Math.floor(Math.random() * mockMessageList.length)];
          const newMessage = {
            type: 'message',
            data: {
              userId: randomUser.userId,
              message: {
                messageId: 'msg' + Date.now(),
                from: randomUser.userId,
                content: '这是一条新消息',
                time: Date.now(),
                read: false,
              },
            },
          };
          callback(JSON.stringify(newMessage));
        }
      }, 5000);
    },
    send: (data) => {
      console.log('发送消息:', data);
    },
    close: () => {
      console.log('关闭WebSocket连接');
    },
  };
  
  return mockSocket;
}

/** 获取消息列表 */
function fetchMessageList() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        success: true,
        data: mockMessageList,
      });
    }, 300);
  });
}

/** 标记消息为已读 */
function markMessagesRead(userId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const user = mockMessageList.find(u => u.userId === userId);
      if (user) {
        user.messages.forEach(msg => {
          if (msg.from !== 'me') {
            msg.read = true;
          }
        });
      }
      resolve({
        success: true,
        data: null,
      });
    }, 100);
  });
}

// 导出所有函数
module.exports = {
  fetchUnreadNum,
  connectSocket,
  fetchMessageList,
  markMessagesRead,
  // 兼容旧的导出格式
  success: true,
  data: {
    data: mockMessageList.map(user => ({
      id: user.userId,
      name: user.name,
      avatar: user.avatar,
      content: user.messages[user.messages.length - 1]?.content || '',
      timestamp: user.messages[user.messages.length - 1]?.time || Date.now(),
      isMe: false,
    })),
  },
};
